<template>
  <!-- :confirm-loading="confirmLoading"   -->
  <a-modal
    title="填报预算"
    :visible="visible"
    :destroyOnClose="true"
    :maskClosable="false"
    :footer="null"
    @cancel="handleCancel">
    <div style="margin-top: 12px;">
      <a-form-model ref="ruleAddForm" :model="addForm" :rules="addRules">
        <a-form-model-item label="门店" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storeId">
          <a-select placeholder="请选择门店" v-model="addForm.storeId" >
            <a-select-option :value="item.storeId" v-for="(item, index) in storesList" :key="index">{{
              item.storeName
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="预算周期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="type">
          <a-select placeholder="请选择预算周期" v-model="addForm.type" @change="selectType">
            <a-select-option :value="item.id" v-for="(item, index) in typeList" :key="index">{{
              item.name
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="预算日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="budgetDate">
          <a-date-picker
            placeholder="请选择预算开始日期"
            v-model="addForm.budgetDate"
            :value-format="formatTime"
            style="width: 100%;" />
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ offset: 5, span: 16 }">
          <a-button type="primary" @click="handleSearch">查询</a-button>
          <a-button
            type="primary"
            @click="handleSubmit"
            v-show="headersSource.length > 0"
            style="margin-left: 20px;"
            :visible="visibleBtn"
            :loading="loadingBtn">填报</a-button>
        </a-form-model-item>
      </a-form-model>
      <table class="vtable" v-show="headersSource.length > 0">
        <thead>
          <div style="background-color: #e8e8e8;display: flex;">
            <div
              style="flex: 1;"
              v-for="(item, index) in headersSource"
              :key="index"
              :style="item.hidden ? 'display: none;' : ''">
              <th class="thead-th" v-if="index != 0" style="display: flex;">
                <span v-if="index != 0" style="display: inline-block;flex: 1;">{{ item.name }}</span>
              </th>
            </div>
          </div>
        </thead>
        <tbody>
          <div v-for="(row, rowId) in newdataSource " :key="rowId" style="display: flex;">
            <tr style="height: 40px;display: flex;" v-if="newdataSource.length > 0 ? row.datas[0] : false">
              <template v-for="(it, itId) in row.datas">
                <div v-if="headersSource[itId].hidden == false">
                  <template v-if="!headersSource[itId].primary">
                    <a-input class="row-td" :value="it" :disabled="true" />
                  </template>
                  <template v-else>
                    <a-input
                      class="row-td"
                      :value="it"
                      type="number"
                      @change="e => handleChange(e.target.value, rowId, itId)"
                      :disabled="false" />
                  </template>
                </div>
              </template>
            </tr>
            <tr style="height: 40px;display: flex;" v-else>
              <template v-for="(it, itId) in row.datas">
                <div v-if="headersSource[itId].hidden == false">
                  <a-input class="row-td" :value="it" :disabled="true" />
                </div>
              </template>
            </tr>
          </div>
        </tbody>
      </table>
    </div>
  </a-modal>
</template>

<script>
import { getBudgetsLaunch, addProjectData } from '@/api/budget'
import { getStores } from '@/api/stores'
export default {
    data () {
        return {

            visible: false,
            confirmLoading: false,
            loading: false,
            visibleBtn: false,
            loadingBtn: false,
            addRules: {
                budgetDate: [
                    { required: true, message: '请选择预算开始日期!', trigger: 'change' }
                ],
                type: [
                    { required: true, message: '请选择预算周期!', trigger: 'change' }
                ],
                storeId: [
                    { required: true, message: '请选择门店!', trigger: 'change' }
                ]
            },
            addForm: {
                type: undefined,
                budgetDate: '',
                storeId: ''
            },
            typeList: [
                { id: 1, name: '年度预算' },
                { id: 2, name: '月度预算' }
            ],

            //  表单样式
            labelCol: {
                xs: { span: 24 },
                sm: { span: 5 }
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 16 }
            },

            formatTime: 'YYYY-MM-DD',
            headersSource: [],
            dataSource: [],
            newdataSource: [],
            newArr: [], // 保存修改的id
            storesList: []
        }
    },
    methods: {
        // 计算比率
        // 本月比上月情况=（本月数字-上月数字）/上月数字，如果本月大于上月，结果就是正数，即上升，反之为下降
        rateCompute (a, b) {
            if (a > 0 || b > 0) {
                if (a > b) return Math.round(((b - a) / a) * 100) + '%'
                else if (b > a) return Math.round(((b - a) / b) * 100) + '%'
                else return '0%'
            } else {
                return '0%'
            }
        },
        // 获取填报改变的值
        handleChange (value, rowId, itId) {
            console.log(value, rowId, itId)
            if (value > 0) { // 01 = > 1
                if (value[0] == 0) {
                    value = value.substr(1)
                }
            } else if (value == 0) { // 00 => 0
                value = value.slice(0, 1)
            }
            // 从当前位置截取数组
            const parentArr = this.newdataSource.slice(rowId)
            // 满足条件的需要统计的下标
            let currentParentId = parentArr.findIndex((item) => item.datas[0] === '')
            // 当前统计的下标
            currentParentId = rowId + currentParentId
            // 上一个统计的下标
            const preArr = this.newdataSource.slice(0, rowId)
            const preParentId = preArr.findLastIndex((item) => item.datas[0] === '')
            console.log(preParentId)
            console.log(currentParentId)
            this.newdataSource.forEach((item, index) => {
                if (index == rowId) {
                    item.datas.splice(itId, 1, value)
                    // 获取上个月和当前预算的数据，动态改变提升利率
                    const pre = item.datas[itId - 1]
                    const now = item.datas[itId]
                    item.datas.splice(itId + 1, 1, this.rateCompute(Number(pre), Number(now)))
                    if (item.datas[0] != '') this.newArr.push(item.datas[0])
                    this.newArr = Array.from(new Set(this.newArr))
                }
            })
            let total = 0
            this.newdataSource.forEach((item, index) => {
                if (index > preParentId && index <= currentParentId - 1) {
                    total += item.datas[itId]
                    console.log(total)
                }
            })
        },
        selectType (value) {
            if (value == 1) this.formatTime = 'YYYY'
            else this.formatTime = 'YYYY-MM-DD'
        },
        // 显示
        open () {
            this.visible = true
            getStores({ storeName: '' }).then(res => {
                if (res.code == 200) {
                    this.storesList = res.data
                    // this.pagination.total = res.data.total
                }
            })
            return this
        },

        // 关闭
        handleCancel () {
            this.visible = false
            this.loadingBtn = false
            this.visibleBtn = false
            this.$emit('close')
        },
        // 确认
        handleSubmit () {
            // 获取项目id 的下标
            const projectId = (this.headersSource || []).findIndex((item) => item.columnId === 'projectId')
            const filterArr = this.newdataSource.filter(item => {
                return this.newArr.includes(item.datas[projectId])
            })
            // 获取需要填报的下标
            const budgetAmountId = (this.headersSource || []).findIndex((item) => item.primary === true)
            let objectArr = []
            objectArr = filterArr.map(item => {
                const obj = {}
                if (item.datas[budgetAmountId] > 0) {
                    // 获取项目id和项目值
                    obj.projectId = item.datas[projectId]
                    obj.value = item.datas[budgetAmountId]
                    return obj
                } else {
                    return ''
                }
            }).filter(item => item)
            if (objectArr.length == 0) {
                this.$notification['error']({
                    message: '提示',
                    description: '请编辑预算项目',
                    duration: 8
                })
                return
            }
            this.loadingBtn = true
            this.visibleBtn = true
            this.$refs.ruleAddForm.validate(valid => {
                if (valid) {
                    const { type, budgetDate } = this.addForm
                    const par = {
                        type,
                        dateTime: budgetDate,
                        projects: objectArr
                    }
                    addProjectData(par).then(res => {
                        if (res.code === 200) {
                            this.$notification['success']({
                                message: '提示',
                                description: '填报成功！',
                                duration: 8
                            })
                            this.visible = false
                            this.$emit('success')
                        } else {
                            this.$notification['error']({
                                message: '提示',
                                description: res.message,
                                duration: 8
                            })
                        }
                        this.visibleBtn = false
                        this.loadingBtn = false
                    })
                } else {
                    this.loadingBtn = false
                    this.visibleBtn = false
                    return false
                }
            })
        },
        // 搜索
        handleSearch () {
            this.$refs.ruleAddForm.validate(valid => {
                if (valid) {
                    getBudgetsLaunch(this.addForm).then(res => {
                        console.log(res)
                        if (res.code == 200) {
                            this.dataSource = res.data.lines
                            const lines = res.data.lines
                            // this.headersSource = res.data.headers
                            // this.newdataSource = res.data.lines
                            this.headersSource = res.data.headers
                            this.headersSource.push({
                                'columnId': '',
                                'name': '提升比率',
                                'hidden': false,
                                'primary': false
                            })
                            // 获取填报的下标
                            const budgetAmountId = (this.headersSource || []).findIndex((item) => item.primary === true)
                            this.newdataSource = lines.map((item, index) => {
                                if (index == budgetAmountId) {
                                    // 根据填报位置，获取上一个月份的信息
                                    const pre = item.datas[index - 1]
                                    const now = item.datas[budgetAmountId]
                                    item.datas.push(this.rateCompute(Number(pre), Number(now)))
                                } else {
                                    item.datas.push('0%')
                                }
                                const obj = {
                                    ...item
                                }
                                return obj
                            })
                        } else {
                            this.$notification['error']({
                                message: '提示',
                                description: res.message,
                                duration: 8
                            })
                        }
                        this.loading = false
                    })
                } else {

                }
            })
        }
    }
}
</script>
<style scoped>
.vtable {
    height: 400px;
    overflow-y: auto;
    overflow-x: hidden;
}

.thead-th {
    width: 100%;
    padding: 10px;

}

.row-td {
    width: 100%;
    padding: 10px;
    border: 1px solid #e8e8e8;
    margin: -5px 0;
    flex: 1;
}
</style>
